<template>
  <div v-loading="pageLoading" :class="{'mobile-detail-wrap': showMobilePage}" class="detail-order-info">
    <template v-if="!permissionDenied">
      <div>
        <Title title="基础信息" style="margin-bottom:10px;"/>
        <el-row class="detail-row">
          <el-form :class="{'mobile-el-form': showMobilePage}" :label-position="showMobilePage ? 'left' : 'right'" label-width="125px">
            <el-col :span="8">
              <el-form-item label="创建人:">
                <CheckUserInfo v-if="data.creator" :label="data.creator" :user-id="data.creatorId" />
                <div v-else>--</div>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="所属部门:">
                <ToolTip :content="data.department" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="提交认证人:">
                <CheckUserInfo v-if="data.submitter" :label="data.submitter" :user-id="data.pushAuthenticatorId" />
                <div v-else>--</div>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="执行认证人:">
                <CheckUserInfo v-if="data.executor" :label="data.executor" :user-id="data.execAuthenticatorId" />
                <div v-else>--</div>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="发票状态:">
                <ToolTip :content="data.invoiceStatus | inputInvoiceStatus" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="发票类型:">
                <span>{{ data.invoiceType | inputInvoiceType }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="发票代码:">
                <ToolTip :content="data.invoiceCode" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="发票号码:">
                <ToolTip :content="data.invoiceNo" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="开票日期:">
                <ToolTip :content="format(data.invoiceDate, 'YYYY/MM/DD')" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="销方名称:">
                <ToolTip :content="data.sellerName" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="销方税号:">
                <ToolTip :content="data.channelTaxId" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="地址:">
                <ToolTip :content="data.address" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="电话:">
                <ToolTip :content="data.telephone" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="开户行:">
                <ToolTip :content="data.bank" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="开户账号:">
                <ToolTip :content="data.bankAccount" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="业务会计:">
                <CheckUserInfo v-if="data.businessAccounting" :label="data.businessAccounting" :user-id="data.businessAccountingId" />
                <div v-else>--</div>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="跟进人:">
                <CheckUserInfo v-if="data.followUsers" :user-list="data.followUsers" multiple label-name="userName"/>
                <div v-else>--</div>
              </el-form-item>
            </el-col>
          </el-form>
        </el-row>
      </div>
      <div class="detail-part">
        <Title title="开票信息" style="margin-bottom:10px;"/>
        <el-row class="detail-row">
          <el-form :class="{'mobile-el-form': showMobilePage}" :label-position="showMobilePage ? 'left' : 'right'" label-width="125px">
            <el-col :span="8">
              <el-form-item label="发票项目:">
                <ToolTip :content="data.invoiceProject" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="单位:">
                <ToolTip :content="data.unit" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="规格型号:">
                <ToolTip :content="data.specification" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="数量:">
                <ToolTip :content="data.quantity" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="单价(元):">
                <PriceColumn :real-val="data.unitPrice" :price="data.unitPrice" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="不含税金额(元):">
                <div class="flex-center">
                  <PriceColumn :real-val="data.money" :price="data.money" />
                  <el-tooltip :open-delay="800" placement="top" effect="dark">
                    <div slot="content" style="max-width: 210px">
                      <p class="tip-p">自动计算参考值={{ money }}</p>
                      <p class="tip-p">不含税金额=含税金额-税额</p>
                    </div>
                    <tipIcon is-diy style="margin-left:4px;"/>
                  </el-tooltip>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="税率:">
                <div v-if="data.taxRate" class="flex-center">
                  <span>{{ data.taxRate }}%</span>
                  <el-tooltip :open-delay="800" placement="top" effect="dark">
                    <div slot="content" style="max-width: 210px">
                      <p class="tip-p">自动计算参考值={{ taxRate }}</p>
                      <p class="tip-p">税率=税额/不含税金额</p>
                    </div>
                    <tipIcon is-diy style="margin-left:4px;"/>
                  </el-tooltip>
                </div>
                <div v-else>--</div>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="税额(元):">
                <PriceColumn :real-val="data.taxAmount" :price="data.taxAmount" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="含税金额(元):">
                <PriceColumn :real-val="data.invoicePrice" :price="data.invoicePrice" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="实际销方名称:">
                <ToolTip :content="data.realChannelName" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="购方名称:">
                <ToolTip :content="data.buyerName" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="票据附件:">
                <FileShowList v-if="showAttachment" :file-list="data.attachmentUrl" style="max-width:100%;" is-show-single-file />
                <span v-else>--</span>
              </el-form-item>
            </el-col>
          </el-form>
        </el-row>
      </div>
      <div class="detail-part">
        <Title title="认证信息" style="margin-bottom:10px;"/>
        <el-form :class="{'mobile-el-form': showMobilePage}" :label-position="showMobilePage ? 'left' : 'right'" label-width="125px" style="width: 100%">
          <el-row class="detail-row certify-info-box" type="flex">
            <el-col :span="8">
              <el-form-item label="进项认证抵扣期:">
                <span>{{ format(data.certifyDeductPeriod, 'YYYY/MM/DD') || '--' }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="抵扣税额(元):">
                <PriceColumn :real-val="data.deductTaxAmount" :price="data.deductTaxAmount" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="文建抵扣期:">
                <span>{{ format(data.culturalConstructDeductPeriod, 'YYYY/MM/DD') || '--' }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="文建抵扣金额(元):">
                <PriceColumn :real-val="data.deductAmount " :price="data.deductAmount" />
              </el-form-item>
            </el-col>
            <el-col :span="8" class="label-collapse-global">
              <el-form-item label="不可抵文建金额(元):">
                <PriceColumn :real-val="data.nonCulturalConstructAmount" :price="data.nonCulturalConstructAmount" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="进项税额转出(元):">
                <PriceColumn :real-val="data.taxTransferOut" :price="data.taxTransferOut" />
              </el-form-item>
            </el-col>
            <el-col :span="8" class="label-collapse-global">
              <el-form-item label="进项税额转出原因:">
                <ToolTip :content="data.taxTransferOutReason" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="进项税额转出期:">
                <span>{{ format(data.taxTransferOutDate, 'YYYY/MM/DD') || '--' }}</span>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div class="detail-part">
        <Title title="关联付款申请" style="margin-bottom: 16px;">
          <div v-if="!showMobilePage" class="data-container">
          <dataDisplay :data-list="dataList"/>
          </div>
        </Title>
        <div v-if="showMobilePage" class="data-container" style="margin-bottom: 12px;">
          <dataDisplay :data-list="dataList"/>
        </div>
        <u-table
          v-if="withdrawData.length > 0"
          :data="withdrawList"
          :row-height="49"
          :border="true"
          beautify-table
          header-drag-style
          use-virtual
          class="fb-table"
          element-loading-text="加载中..."
          empty-text="暂无数据"
          header-cell-class-name="order-data-header-cell "
          fit
          hightlight-current-row>
          <u-table-column align="left" label="审批单号" min-width="200" label-class-name="diy-cell" class-name="diy-cell">
            <template slot-scope="scope" slot="header">
              <div class="diyHeader">{{ scope.column.label }}</div>
            </template>
            <template slot-scope="scope">
              <processSn :is-expedited="scope.row.isExpedited">
                <span style="cursor:pointer;color:#406EFF" @click="toCheck(scope.row)">{{ scope.row.examineId || '--' }}</span>
              </processSn>
            </template>
          </u-table-column>
          <u-table-column align="left" label="结算名称" min-width="150">
            <template slot-scope="scope">
              <ToolTip :content="scope.row.settlementName" />
            </template>
          </u-table-column>
          <u-table-column align="right" label="结算金额(元)" min-width="120">
            <template slot-scope="scope">
              <PriceColumn :real-val="scope.row.settlementAmount" :price="scope.row.settlementAmount / 100" />
            </template>
          </u-table-column>
          <u-table-column align="right" label="实付金额(元)" min-width="120">
            <template slot-scope="scope">
              <PriceColumn :real-val="scope.row.actualAmount" :price="scope.row.actualAmount / 100" />
            </template>
          </u-table-column>
          <u-table-column align="left" label="当前节点" min-width="100">
            <template slot-scope="scope">
              <ToolTip :content="scope.row.workflowNodeName" />
            </template>
          </u-table-column>
          <u-table-column align="left" label="状态">
            <template slot-scope="scope">
              <StatusText
                v-if="scope.row.examineStatus || scope.row.examineStatus===0"
                :color="['#FFBC3D','#FD8546', '#FF4E5F', '#999', '#31CC9C','#406EFF'][scope.row.examineStatus]"
                :text="scope.row.examineStatus | examineStatus"
              />
              <div v-else>--</div>
            </template>
          </u-table-column>
          <u-table-column align="left" label="创建人">
            <template slot-scope="scope">
              <CheckUserInfo v-if="scope.row.creator" :label="scope.row.creator" :user-id="scope.row.creatorId" />
              <div v-else>--</div>
            </template>
          </u-table-column>
          <u-table-column align="left" label="创建时间" min-width="150">
            <template slot-scope="scope">
              <span>{{ scope.row.createTime | format('YYYY/MM/DD HH:mm') }}</span>
            </template>
          </u-table-column>
        </u-table>
        <empty-placeholder v-else style="margin-bottom: 24px" />
        <div style="text-align: right;">
          <el-pagination
            v-show="withdrawData.length > 10"
            :current-page="withdrawPage"
            :page-size="withdrawPerPage"
            :total="withdrawData.length"
            :page-sizes="[10, 20, 50, 100, 250, 500]"
            layout="total, prev, pager, next, sizes, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange" />
        </div>
      </div>
      <div class="detail-part">
        <Title title="操作日志" style="margin-bottom:16px;"/>
        <div v-if="logData && logData.length">
          <log-time-line :logs="logData || []" :is-show-edit="false" :is-fold="true"/>
        </div>
        <EmptyPlaceholder v-else no-border empty-text="暂无操作日志" style="margin: 28px 0" />
      </div>
      <fixed-pagination>
        <div v-if="showMobilePage" class="center">
          <MoreOperateBtn>
            <el-dropdown-item v-if="data.invoiceStatus === 1 && hasRouteAuth('crm:inputInvoice:submit')" style="width:80px;text-align: center" @click.native="handleOperate(0, '提交认证')">
              <div>提交认证</div>
            </el-dropdown-item>
            <el-dropdown-item v-if="data.invoiceStatus === 1 && hasRouteAuth('crm:inputInvoice:submit')" style="width:80px;text-align: center" @click.native="handleOperate(1, '无需认证')">
              <div>无需认证</div>
            </el-dropdown-item>
            <el-dropdown-item v-if="data.invoiceStatus === 2 && hasRouteAuth('crm:inputInvoice:confirm')" style="width:80px;text-align: center" @click.native="handleOperate(2, '确认认证')">
              <div>确认认证</div>
            </el-dropdown-item>
            <el-dropdown-item v-if="data.invoiceStatus === 3 && hasRouteAuth('crm:inputInvoice:withdraw')" style="width:80px;text-align: center" @click.native="handleOperate(3, '撤回待认证')">
              <div>撤回待认证</div>
            </el-dropdown-item>
            <el-dropdown-item v-if="data.invoiceStatus === 3 && hasRouteAuth('crm:inputInvoice:withdraw')" style="width:80px;text-align: center" @click.native="handleOperate(4, '撤回')">
              <div>撤回</div>
            </el-dropdown-item>
          </MoreOperateBtn>
          <el-button v-if="[0,1,2].includes(data.invoiceStatus) && hasRouteAuth('crm:inputInvoice:edit')" type="primary" size="small" @click="toEdit">编辑</el-button>
          <el-button type="info" class="cancel-btn-style" size="small" @click="toBack"><span style="font-size:14px;">返回</span></el-button>
        </div>
        <div v-else class="center">
          <el-button v-if="data.invoiceStatus === 1 && hasRouteAuth('crm:inputInvoice:submit')" type="primary" size="small" @click="handleOperate(0, '提交认证')">提交认证</el-button>
          <el-button v-if="data.invoiceStatus === 1 && hasRouteAuth('crm:inputInvoice:submit')" type="danger" plain size="small" @click="handleOperate(1, '无需认证')">无需认证</el-button>
          <el-button v-if="data.invoiceStatus === 2 && hasRouteAuth('crm:inputInvoice:confirm')" type="primary" size="small" @click="handleOperate(2, '确认认证')">确认认证</el-button>
          <el-button v-if="data.invoiceStatus === 2 && hasRouteAuth('crm:inputInvoice:confirm')" type="danger" plain size="small" @click="handleOperate(3, '撤回待认证')">撤回待认证</el-button>
          <el-button v-if="data.invoiceStatus === 3 && hasRouteAuth('crm:inputInvoice:withdraw')" type="danger" plain size="small" @click="handleOperate(4, '撤回')">撤回</el-button>
          <el-button v-if="[0,1,2].includes(data.invoiceStatus) && hasRouteAuth('crm:inputInvoice:edit')" type="primary" size="small" @click="toEdit">编辑</el-button>
          <el-button type="info" class="cancel-btn-style" size="small" @click="toBack"><span style="font-size:14px;">返回</span></el-button>
        </div>
      </fixed-pagination>
    </template>
    <DeniedPlaceholder v-else />
  </div>
</template>

<script>
import emptyImg from '@/assets/empty-data-icon.png';
import FileShowList from '@/components/CreateOrder/fileShowList';
import LogTimeLine from '@/components/Common/logTimeLine';
import EmptyPlaceholder from '@/components/Common/emptyPlaceholder';
import dataDisplay from '@/components/Common/baseComponent/dataDisplay';
import MoreOperateBtn from '@/components/Common/mobileComponents/moreOperate';
import Title from '@/components/Title';
import { getInputInvoiceDetail, getInputInvoicelog, operateInputInvoice, getWithdrawInfo } from '@/api/inputInvoice';
import { showModal } from '@/utils/message';
import { inputInvoiceStatus, inputInvoiceType, examineStatus } from '@/filters/status';
import { format } from '@/filters/date';
import { hasRouteAuth } from '@/utils/permission';
import icon_17 from '@/assets/dataDisplay/icon_17.png';
import { mapState } from 'vuex';

export default {
  components: { Title, LogTimeLine, FileShowList, EmptyPlaceholder, dataDisplay, MoreOperateBtn },
  filters: { inputInvoiceStatus, inputInvoiceType, examineStatus, format },
  data() {
    return {
      emptyImg,
      id: null,
      data: {},
      logData: [],
      logOpen: false,
      pageLoading: false,
      permissionDenied: false, // 详情页是否可查看
      withdrawData: [],
      withdrawPage: 1,
      withdrawPerPage: 10,
      money: 0,
      taxRate: '--'
    };
  },
  computed: {
    ...mapState({
      'showMobilePage': state => state.app.showMobilePage
    }),
    withdrawList() {
      return this.withdrawData.slice((this.withdrawPage - 1) * this.withdrawPerPage, this.withdrawPage * this.withdrawPerPage);
    },
    dataList() {
      if (this.withdrawData.length === 0) {
        return [
          { label: '结算金额', data: 0, icon: icon_17, width: '200px' },
          { label: '实付金额', data: 0, icon: icon_17, width: '200px' }
        ];
      }
      let settlementAmount = this.withdrawData.reduce((pre, next) => {
        return Number(pre) + Number(next.settlementAmount);
      }, 0);
      settlementAmount = (settlementAmount / 100).toFixed(2);
      let actualAmount = this.withdrawData.reduce((pre, next) => {
        return Number(pre) + Number(next.actualAmount);
      }, 0);
      actualAmount = (actualAmount / 100).toFixed(2);
      return [
        { label: '结算金额', data: settlementAmount, icon: icon_17, width: '200px' },
        { label: '实付金额', data: actualAmount, icon: icon_17, width: '200px' }
      ];
    },
    showAttachment() {
      if (!(this.data.attachmentUrl && this.data.attachmentUrl.length > 0)) {
        return false;
      } else {
        const urlList = this.data.attachmentUrl.map(item => item.url);
        return !urlList.includes(null);
      }
    }
  },
  created() {
    this.id = this.$route.query.id;
    this.getDetailData();
    this.getLogData();
  },
  methods: {
    format,
    hasRouteAuth,
    formatApprovalNumber(data) {
      const dataHtml = data.split(',').map(item => {
        return '<span>' + item + '</span>';
      }).join('<br/>');
      return dataHtml;
    },
    toEdit() {
      this.$router.push({
        name: 'inputInvoiceEdit',
        query: { id: this.id }
      });
    },
    async getDetailData() {
      try {
        this.pageLoading = true;
        const { data } = await getInputInvoiceDetail(this.id);
        if (data.withdrawIds) {
          this.getWithdrawData(data.withdrawIds);
        }
        this.data = data;
        this.money = (Number(data.invoicePrice || 0) - Number(data.taxAmount || 0)).toFixed(2);
        this.taxRate = data.money ? ((Number(data.taxAmount || 0) / data.money) * 100).toFixed(2) + '%' : '--';
        this.pageLoading = false;
      } catch (err) {
        if (err.code === 403) this.permissionDenied = true;
        this.pageLoading = false;
      }
    },
    async getWithdrawData(ids) {
      try {
        const { data } = await getWithdrawInfo({ ids: ids });
        this.withdrawData = data;
      } catch (err) {
        console.log(err);
      }
    },
    async getLogData() {
      try {
        const { data } = await getInputInvoicelog({ id: this.id });
        this.logData = data.items;
      } catch (err) {
        console.log(err);
      }
    },
    handleOperate(certificateType, label) {
      // 提交认证
      showModal(`是否${label}?`, '', {
        iconClass: 'del-icon'
      }).then(() => {
        const params = { certificateType, ids: this.id };
        operateInputInvoice(params).then(res => {
          this.getDetailData();
          this.getLogData();
          this.$message.success('操作成功');
        }).catch(err => { console.log(err); });
      }).catch(() => {
        return false;
      });
    },
    toBack() {
      this.$router.push({ name: 'inputInvoice' });
    },
    toCheck(item) {
      const query = {
        settleId: item.settleId,
        id: item.id,
        isSettle: true,
        fromList: 1,
        fromInputInvoice: 1
      };
      const url = this.$router.resolve({
        name: 'supplierDetail',
        query
      });
      window.open(url.href, '_blank');
    },
    handleSizeChange(val) {
      this.withdrawPerPage = val;
    },
    handleCurrentChange(toPage) {
      this.withdrawPage = toPage;
    }
  }
};
</script>

<style lang="scss" scoped>
.detail-order-info {
  margin: 16px;
  padding: 16px 24px 55px;
  background: #fff;
  min-height: calc(100vh - 80px);
  &.mobile-detail-wrap {
    margin: 0px;
    padding: 12px 12px 55px 12px;
  }
  &::v-deep {
    .el-col {
      .el-form-item{
        margin-bottom: 0;
      }
      .el-form-item__content {
        border-right: 1px solid #EBEEFD !important;
      }
      &:nth-child(3n) {
        .el-form-item__content {
          border-right: none !important;
        }
      }
      &:last-child {
        .el-form-item__content {
          border-right: none;
        }
      }
    }
    .el-form-item .el-form-item__label {
      color: #999;
    }
    .el-form-item .el-form-item__content {
      color: #333;
    }
  }
  &.mobile-detail-wrap {
    ::v-deep .el-col {
      .el-form-item__content {
        border-right: none !important;
      }
    }
    ::v-deep .operating-record {
      .el-timeline-item__wrapper {
        .el-timeline-item__content {
          overflow: auto;
          .ellipsis {
            overflow: unset;
          }
          .detail {
            width: fit-content;
          }
        }
      }
    }
  }
  .certify-info-box {
    flex-wrap: wrap;
    &::v-deep {
      .el-col-8 {
        flex-shrink: 0;
      }
    }
  }
}
.detail-part {
  margin-top: 25px;
}
.data-container {
  margin-left: 10px;
}
.tip-p {
  padding: 0;
  margin: 0;
  text-align: center;
}
</style>
